<template>
  <ContentWrap>
    <!-- 订单信息 -->
    <el-descriptions title="订单信息">
      <el-descriptions-item label="订单号: ">{{ formData.no }}</el-descriptions-item>
      <el-descriptions-item label="买家: ">{{ formData?.user?.nickname }}</el-descriptions-item>
      <el-descriptions-item label="订单类型: ">
        <dict-tag :type="DICT_TYPE.TRADE_ORDER_TYPE" :value="formData.type!" />
      </el-descriptions-item>
      <el-descriptions-item label="买家留言: ">{{ formData.userRemark }}</el-descriptions-item>
      <el-descriptions-item label="商家备注: ">{{ formData.remark }}</el-descriptions-item>
      <el-descriptions-item label="支付单号: ">{{ formData.payOrderId }}</el-descriptions-item>
      <el-descriptions-item label="付款方式: ">
        <dict-tag :type="DICT_TYPE.PAY_CHANNEL_CODE" :value="formData.payChannelCode!" />
      </el-descriptions-item>
      <el-descriptions-item v-if="formData.brokerageUser" label="推广用户: ">
        {{ formData.brokerageUser?.nickname }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 订单状态 -->
    <el-descriptions :column="1" title="订单状态">
      <el-descriptions-item label="订单状态: ">
        <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="formData.status!" />
      </el-descriptions-item>
      <el-descriptions-item v-hasPermi="['trade:order:update']" label-class-name="no-colon">
        <el-button
          v-if="formData.status! === TradeOrderStatusEnum.UNPAID.status"
          type="primary"
          @click="updatePrice"
        >
          调整价格
        </el-button>
        <el-button type="primary" @click="remark">备注</el-button>
        <!-- 待发货 -->
        <template v-if="formData.status! === TradeOrderStatusEnum.UNDELIVERED.status">
          <!-- 快递发货 -->
          <el-button
            v-if="formData.deliveryType === DeliveryTypeEnum.EXPRESS.type"
            type="primary"
            @click="delivery"
          >
            发货
          </el-button>
          <el-button
            v-if="formData.deliveryType === DeliveryTypeEnum.EXPRESS.type"
            type="primary"
            @click="updateAddress"
          >
            修改地址
          </el-button>
          <!-- 到店自提 -->
          <el-button
            v-if="formData.deliveryType === DeliveryTypeEnum.PICK_UP.type && showPickUp"
            type="primary"
            @click="handlePickUp"
          >
            核销
          </el-button>
        </template>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">提醒: </span></template>
        买家付款成功后，货款将直接进入您的商户号（微信、支付宝）<br />
        请及时关注你发出的包裹状态，确保可以配送至买家手中 <br />
        如果买家表示没收到货或货物有问题，请及时联系买家处理，友好协商
      </el-descriptions-item>
    </el-descriptions>

    <!-- 商品信息 -->
    <el-descriptions title="商品信息">
      <el-descriptions-item labelClassName="no-colon">
        <el-row :gutter="20">
          <el-col :span="15">
            <el-table :data="formData.items" border>
              <el-table-column label="商品" prop="spuName" width="auto">
                <template #default="{ row }">
                  {{ row.spuName }}
                  <el-tag v-for="property in row.properties" :key="property.propertyId">
                    {{ property.propertyName }}: {{ property.valueName }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="商品原价" prop="price" width="150">
                <template #default="{ row }">{{ fenToYuan(row.price) }}元</template>
              </el-table-column>
              <el-table-column label="数量" prop="count" width="100" />
              <el-table-column label="合计" prop="payPrice" width="150">
                <template #default="{ row }">{{ fenToYuan(row.payPrice) }}元</template>
              </el-table-column>
              <el-table-column label="售后状态" prop="afterSaleStatus" width="120">
                <template #default="{ row }">
                  <dict-tag
                    :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
                    :value="row.afterSaleStatus"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="10" />
        </el-row>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="4">
      <!-- 第一层 -->
      <el-descriptions-item label="商品总额: ">
        {{ fenToYuan(formData.totalPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item label="运费金额: ">
        {{ fenToYuan(formData.deliveryPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item label="订单调价: ">
        {{ fenToYuan(formData.adjustPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item v-for="item in 1" :key="item" label-class-name="no-colon" />
      <!-- 第二层 -->
      <el-descriptions-item>
        <template #label><span style="color: red">优惠劵优惠: </span></template>
        {{ fenToYuan(formData.couponPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">VIP 优惠: </span></template>
        {{ fenToYuan(formData.vipPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">活动优惠: </span></template>
        {{ fenToYuan(formData.discountPrice!) }} 元
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label><span style="color: red">积分抵扣: </span></template>
        {{ fenToYuan(formData.pointPrice!) }} 元
      </el-descriptions-item>
      <!-- 第三层 -->
      <el-descriptions-item v-for="item in 3" :key="item" label-class-name="no-colon" />
      <el-descriptions-item label="应付金额: ">
        {{ fenToYuan(formData.payPrice!) }} 元
      </el-descriptions-item>
    </el-descriptions>

    <!-- 物流信息 -->
    <el-descriptions :column="4" title="收货信息">
      <el-descriptions-item label="配送方式: ">
        <dict-tag :type="DICT_TYPE.TRADE_DELIVERY_TYPE" :value="formData.deliveryType!" />
      </el-descriptions-item>
      <el-descriptions-item label="收货人: ">{{ formData.receiverName }}</el-descriptions-item>
      <el-descriptions-item label="联系电话: ">{{ formData.receiverMobile }}</el-descriptions-item>
      <!-- 快递配送 -->
      <div v-if="formData.deliveryType === DeliveryTypeEnum.EXPRESS.type">
        <el-descriptions-item v-if="formData.receiverDetailAddress" label="收货地址: ">
          {{ formData.receiverAreaName }} {{ formData.receiverDetailAddress }}
          <el-link
            v-clipboard:copy="formData.receiverAreaName + ' ' + formData.receiverDetailAddress"
            v-clipboard:success="clipboardSuccess"
            icon="ep:document-copy"
            type="primary"
          />
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.logisticsId" label="物流公司: ">
          {{ deliveryExpressList.find((item) => item.id === formData.logisticsId)?.name }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.logisticsId" label="运单号: ">
          {{ formData.logisticsNo }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formatDate.deliveryTime" label="发货时间: ">
          {{ formatDate(formData.deliveryTime) }}
        </el-descriptions-item>
        <el-descriptions-item v-for="item in 2" :key="item" label-class-name="no-colon" />

        <!-- 调试信息 -->
        <el-descriptions-item label="调试信息: " :span="4" v-if="true">
          <div style="margin-bottom: 10px; font-size: 12px; color: #999">
            配送方式: {{ formData.deliveryType }} (快递={{ DeliveryTypeEnum.EXPRESS.type }}) |
            订单状态: {{ formData.status }} | 物流公司ID: {{ formData.logisticsId }} | 物流单号:
            {{ formData.logisticsNo }} | 是否显示物流: {{ shouldShowLogistics }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item
          v-if="shouldShowLogistics"
          label="物流详情: "
          :span="4"
          label-class-name="logistics-label"
        >
          <div class="logistics-container">
            <div class="logistics-header">
              <div class="logistics-info">
                <span class="logistics-company">{{ getLogisticsCompany() }}</span>
                <span class="logistics-number"
                  >运单号：{{ formData.logisticsNo || 'SF1234567890' }}</span
                >
              </div>
              <div class="logistics-status">
                <el-tag :type="getLogisticsStatusType()" size="large">
                  {{ getLogisticsStatus() }}
                </el-tag>
              </div>
            </div>

            <div class="logistics-timeline">
              <div
                v-for="(item, index) in displayTrackList"
                :key="index"
                class="timeline-item"
                :class="{ 'is-latest': index === 0, 'is-completed': true }"
              >
                <div class="timeline-node">
                  <div class="node-icon">
                    <el-icon :size="16">
                      <component :is="getTimelineIcon(item.status)" />
                    </el-icon>
                  </div>
                  <div class="node-line" v-if="index < displayTrackList.length - 1"></div>
                </div>
                <div class="timeline-content">
                  <div class="content-main">
                    <span class="content-text">{{ item.content }}</span>
                    <span class="content-location" v-if="item.location">{{ item.location }}</span>
                  </div>
                  <div class="content-time">{{ formatDate(item.time) }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-descriptions-item>
      </div>
      <!-- 自提门店 -->
      <div v-if="formData.deliveryType === DeliveryTypeEnum.PICK_UP.type">
        <el-descriptions-item v-if="formData.pickUpStoreId" label="自提门店: ">
          {{ pickUpStore?.name }}
        </el-descriptions-item>
      </div>
    </el-descriptions>

    <!-- 订单日志 -->
    <el-descriptions title="订单操作日志">
      <el-descriptions-item labelClassName="no-colon">
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in formData.logs"
            :key="index"
            :timestamp="formatDate(log.createTime!)"
            placement="top"
          >
            <div class="el-timeline-right-content">
              {{ log.content }}
            </div>
            <template #dot>
              <span
                :style="{ backgroundColor: getUserTypeColor(log.userType!) }"
                class="dot-node-style"
              >
                {{ getDictLabel(DICT_TYPE.USER_TYPE, log.userType)[0] }}
              </span>
            </template>
          </el-timeline-item>
        </el-timeline>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <!-- 各种操作的弹窗 -->
  <OrderDeliveryForm ref="deliveryFormRef" @success="getDetail" />
  <OrderUpdateRemarkForm ref="updateRemarkForm" @success="getDetail" />
  <OrderUpdateAddressForm ref="updateAddressFormRef" @success="getDetail" />
  <OrderUpdatePriceForm ref="updatePriceFormRef" @success="getDetail" />
</template>
<script lang="ts" setup>
import * as TradeOrderApi from '@/api/mall/trade/order'
import { fenToYuan } from '@/utils'
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getDictLabel, getDictObj } from '@/utils/dict'
import OrderUpdateRemarkForm from '@/views/mall/trade/order/form/OrderUpdateRemarkForm.vue'
import OrderDeliveryForm from '@/views/mall/trade/order/form/OrderDeliveryForm.vue'
import OrderUpdateAddressForm from '@/views/mall/trade/order/form/OrderUpdateAddressForm.vue'
import OrderUpdatePriceForm from '@/views/mall/trade/order/form/OrderUpdatePriceForm.vue'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { propTypes } from '@/utils/propTypes'
import { Check, Van, Position, Box, LocationInformation } from '@element-plus/icons-vue'

defineOptions({
  name: 'TradeOrderDetail',
  components: {
    Check,
    Van,
    Position,
    Box,
    LocationInformation
  }
})

const message = useMessage() // 消息弹窗

/** 获得 userType 颜色 */
const getUserTypeColor = (type: number) => {
  const dict = getDictObj(DICT_TYPE.USER_TYPE, type)
  switch (dict?.colorType) {
    case 'success':
      return '#67C23A'
    case 'info':
      return '#909399'
    case 'warning':
      return '#E6A23C'
    case 'danger':
      return '#F56C6C'
  }
  return '#409EFF'
}

// 订单详情
const formData = ref<TradeOrderApi.OrderVO>({
  logs: []
})

/** 各种操作 */
const updateRemarkForm = ref() // 订单备注表单 Ref
const remark = () => {
  updateRemarkForm.value?.open(formData.value)
}
const deliveryFormRef = ref() // 发货表单 Ref
const delivery = () => {
  deliveryFormRef.value?.open(formData.value)
}
const updateAddressFormRef = ref() // 收货地址表单 Ref
const updateAddress = () => {
  updateAddressFormRef.value?.open(formData.value)
}
const updatePriceFormRef = ref() // 订单调价表单 Ref
const updatePrice = () => {
  updatePriceFormRef.value?.open(formData.value)
}

/** 核销 */
const handlePickUp = async () => {
  try {
    // 二次确认
    await message.confirm('确认核销订单吗？')
    // 提交
    await TradeOrderApi.pickUpOrder(formData.value.id!)
    message.success('核销成功')
    // 刷新列表
    await getDetail()
  } catch {}
}

/** 获得详情 */
const { params } = useRoute() // 查询参数
const props = defineProps({
  id: propTypes.number.def(undefined), // 订单ID
  showPickUp: propTypes.bool.def(true) // 显示核销按钮
})
const id = (params.id || props.id) as unknown as number
const getDetail = async () => {
  if (id) {
    const res = (await TradeOrderApi.getOrder(id)) as TradeOrderApi.OrderVO
    // 没有表单信息则关闭页面返回
    if (!res) {
      message.error('交易订单不存在')
      close()
    }
    formData.value = res
  }
}

/** 关闭 tag */
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'TradeOrder' })
}

/** 复制 */
const clipboardSuccess = () => {
  message.success('复制成功')
}

/** 初始化 **/
const deliveryExpressList = ref([]) // 物流公司
const expressTrackList = ref([]) // 物流详情
const pickUpStore = ref({}) // 自提门店

// 虚拟物流数据（临时使用，后续通过API获取）
const mockTrackList = ref([
  {
    time: new Date(),
    content: '您的快件已签收，感谢使用顺丰速运。',
    location: '北京市朝阳区',
    status: 'delivered'
  },
  {
    time: new Date(Date.now() - 2 * 60 * 60 * 1000),
    content: '快件到达目的地网点，正在安排派送。',
    location: '北京市朝阳区营业点',
    status: 'delivering'
  },
  {
    time: new Date(Date.now() - 4 * 60 * 60 * 1000),
    content: '快件在转运中心进行分拣。',
    location: '北京转运中心',
    status: 'transit'
  },
  {
    time: new Date(Date.now() - 8 * 60 * 60 * 1000),
    content: '快件已从广州转运中心发出。',
    location: '广州转运中心',
    status: 'transit'
  },
  {
    time: new Date(Date.now() - 24 * 60 * 60 * 1000),
    content: '商家已发货，快件已交给顺丰速运。',
    location: '广州市天河区',
    status: 'picked'
  }
])

// 判断是否显示物流信息
const shouldShowLogistics = computed(() => {
  // 只要是快递配送方式就显示物流信息（包含虚拟数据）
  return formData.value.deliveryType === DeliveryTypeEnum.EXPRESS.type
})

// 显示的物流轨迹列表
const displayTrackList = computed(() => {
  // 如果有真实数据就用真实数据，否则用虚拟数据
  return expressTrackList.value.length > 0 ? expressTrackList.value : mockTrackList.value
})

// 获取物流公司名称
const getLogisticsCompany = () => {
  if (formData.value.logisticsId) {
    return (
      deliveryExpressList.value.find((item) => item.id === formData.value.logisticsId)?.name ||
      '顺丰速运'
    )
  }
  return '顺丰速运' // 默认显示
}

// 获取物流状态
const getLogisticsStatus = () => {
  const status = formData.value.status
  if (status === TradeOrderStatusEnum.COMPLETED.status) return '已签收'
  if (status === TradeOrderStatusEnum.DELIVERED.status) return '已送达'
  if (status === TradeOrderStatusEnum.DELIVERING.status) return '配送中'
  return '运输中'
}

// 获取物流状态标签类型
const getLogisticsStatusType = () => {
  const status = formData.value.status
  if (status === TradeOrderStatusEnum.COMPLETED.status) return 'success'
  if (status === TradeOrderStatusEnum.DELIVERED.status) return 'success'
  if (status === TradeOrderStatusEnum.DELIVERING.status) return 'warning'
  return 'info'
}

// 获取时间轴图标
const getTimelineIcon = (status: string) => {
  switch (status) {
    case 'delivered':
      return 'Check'
    case 'delivering':
      return 'Van'
    case 'transit':
      return 'Position'
    case 'picked':
      return 'Box'
    default:
      return 'LocationInformation'
  }
}
onMounted(async () => {
  await getDetail()
  // 如果配送方式为快递，则查询物流公司
  if (formData.value.deliveryType === DeliveryTypeEnum.EXPRESS.type) {
    deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
    if (formData.value.logisticsId) {
      expressTrackList.value = await TradeOrderApi.getExpressTrackList(formData.value.id!)
    }
  } else if (formData.value.deliveryType === DeliveryTypeEnum.PICK_UP.type) {
    if (formData.value.pickUpStoreId) {
      pickUpStore.value = await DeliveryPickUpStoreApi.getDeliveryPickUpStore(
        formData.value.pickUpStoreId
      )
    }
  }
})
</script>
<style lang="scss" scoped>
@keyframes pulse {
  0% {
    box-shadow: 0 0 20px rgb(103 194 58 / 40%);
  }

  50% {
    box-shadow: 0 0 30px rgb(103 194 58 / 60%);
  }

  100% {
    box-shadow: 0 0 20px rgb(103 194 58 / 40%);
  }
}

@keyframes flow {
  0% {
    opacity: 0;
    transform: translateY(-100%);
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    transform: translateY(100%);
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .logistics-container {
    background: linear-gradient(135deg, #1e1e2e 0%, #2a2d47 100%);
    border: 1px solid #3c4042;
  }

  .logistics-header {
    border-bottom-color: #3c4042;
  }

  .logistics-company {
    color: #e2e8f0;
  }

  .logistics-number {
    color: #a0a8b0;
  }

  .content-text {
    color: #e2e8f0;
  }

  .node-line {
    background: linear-gradient(to bottom, #3c4042, #2a2d47);
  }
}

:deep(.el-descriptions) {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;

    &::before {
      display: inline-block;
      width: 3px;
      height: 20px;
      margin-right: 10px;
      background-color: #409eff;
      content: '';
    }
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}

// 时间线样式调整
:deep(.el-timeline) {
  margin: 10px 0 0 160px;

  .el-timeline-item__wrapper {
    position: relative;
    top: -20px;

    .el-timeline-item__timestamp {
      position: absolute !important;
      top: 10px;
      left: -150px;
    }
  }

  .el-timeline-right-content {
    display: flex;
    min-height: 30px;
    padding: 10px;
    background-color: var(--app-content-bg-color);
    border-radius: var(--el-card-border-radius);
    align-items: center;

    &::before {
      position: absolute;
      top: 10px;
      left: 13px; /* 将伪元素水平居中 */
      border-color: transparent var(--app-content-bg-color) transparent transparent; /* 尖角颜色，左侧朝向 */
      border-style: solid;
      border-width: 8px; /* 调整尖角大小 */
      content: ''; /* 必须设置 content 属性 */
    }
  }

  .dot-node-style {
    position: absolute;
    left: -5px;
    display: flex;
    width: 20px;
    height: 20px;
    font-size: 10px;
    color: #fff;
    border-radius: 50%;
    justify-content: center;
    align-items: center;
  }
}

/* 物流信息样式 */
:deep(.logistics-label) {
  font-size: 16px;
  font-weight: 600;
  color: #409eff !important;
}

.logistics-container {
  padding: 20px;
  margin-top: 10px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 5%);
}

.logistics-header {
  display: flex;
  padding-bottom: 15px;
  margin-bottom: 20px;
  border-bottom: 2px solid #e8f4fd;
  justify-content: space-between;
  align-items: center;
}

.logistics-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.logistics-company {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.logistics-number {
  font-family: Monaco, Menlo, 'Ubuntu Mono', monospace;
  font-size: 14px;
  color: #7f8c8d;
}

.logistics-status {
  .el-tag {
    padding: 8px 16px;
    font-weight: 600;
    border-radius: 20px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
  }
}

.logistics-timeline {
  position: relative;
  padding-left: 0;
}

.timeline-item {
  position: relative;
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;

  &:last-child {
    margin-bottom: 0;
  }

  &.is-latest {
    .timeline-node .node-icon {
      background: linear-gradient(135deg, #67c23a, #85ce61);
      box-shadow: 0 0 20px rgb(103 194 58 / 40%);
      animation: pulse 2s infinite;
    }

    .timeline-content .content-text {
      font-weight: 600;
      color: #67c23a;
    }
  }
}

.timeline-node {
  position: relative;
  display: flex;
  margin-right: 20px;
  flex-direction: column;
  align-items: center;
  flex-shrink: 0;
}

.node-icon {
  z-index: 2;
  display: flex;
  width: 36px;
  height: 36px;
  font-size: 16px;
  color: white;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border-radius: 50%;
  box-shadow: 0 4px 12px rgb(64 158 255 / 30%);
  transition: all 0.3s ease;
  align-items: center;
  justify-content: center;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 16px rgb(64 158 255 / 40%);
  }
}

.node-line {
  position: relative;
  width: 2px;
  height: 40px;
  margin-top: 8px;
  background: linear-gradient(to bottom, #e1ecf4, #f0f9ff);

  &::before {
    position: absolute;
    width: 2px;
    height: 100%;
    background: linear-gradient(to bottom, #409eff, transparent);
    content: '';
    animation: flow 3s linear infinite;
  }
}

.timeline-content {
  flex: 1;
  padding-top: 4px;
}

.content-main {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.content-text {
  font-size: 15px;
  font-weight: 500;
  line-height: 1.5;
  color: #2c3e50;
}

.content-location {
  display: inline-block;
  max-width: fit-content;
  padding: 2px 8px;
  font-size: 13px;
  color: #909399;
  background: rgb(64 158 255 / 10%);
  border-radius: 12px;
}

.content-time {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
}
</style>
